import Vue from 'vue'
import store from '@/store/index.js'

export default {
	token: '',
	userId: 0,
	timeout: 30000, // 30s
	timeoutObj: null,
	// 判断是否已连接
	checkOpenSocket() {
		this.token = store.state.loginInfo.token
		this.userId = store.state.userInfo.id
		const message = {
			cmd: 0,
			user_id: this.userId,
			content: "ping"
		}
		uni.sendSocketMessage({
			data: JSON.stringify(message),
			success: res => {
				return;
			},
			fail: err => {
				// 未连接打开websocket连接
				this.openConnection()
			}
		})
	},
	// 连接
	openConnection() {
		var wsUri = Vue.prototype.$config.ws + "/api/v1/chat?token=" + this.token
		uni.connectSocket({
			url: wsUri,
			success(res) {
				console.log('连接成功 connectSocket=', res)
			},
			fail(err) {
				console.log('连接失败 connectSocket=', err)
			}
		});
		uni.onSocketOpen(res => {
			console.log('启动心跳')
			this.start()
		})
		this.onMessage()
	},
	// 关闭连接
	closeConnect() {
		uni.closeSocket() // WebSocket
		uni.onSocketClose(res => {
			console.log('WebSocket 已关闭！')
			this.compulsoryLogout()
		})
	},
	compulsoryLogout() {
		clearInterval(this.timeoutObj)
		store.dispatch('logout', false)
		uni.reLaunch({
			url: "/pages/auth/login/login"
		})
		return false
	},
	// 监听服务器返回的消息
	onMessage() {
		uni.onSocketMessage(async res => {
			console.log('监听到有新服务器消息：', res.data)
			const rev = JSON.parse(res.data)
			if (rev.cmd == 1) {
				console.log('监听到服务器消息成功')
				// 更新token
				if(rev.auth.token) {
					await store.dispatch('updateTokenAction', rev.auth)
				}
			} else if (rev.cmd == 2) {
				console.log('监听到服务器消息失败，需要退出，关闭心跳')
				this.compulsoryLogout()
			} else {
				this.currentPageMessage(res.data, Vue.prototype.$config.new_message_key)
			}
		})
	},
	// 发送消息
	sendMessage(objMsg) {
		let sendData = JSON.stringify(objMsg)
		return new Promise(function(resolve, reject) {
		    uni.sendSocketMessage({
		    	data: sendData,
		    	success: res => {
		    		console.log("消息发送成功")
					store.dispatch('addNewMessage', sendData)
					resolve(true)
		    	},
		    	fail: err => {
		    		Vue.prototype.$u.toast("服务端链接失败，请稍后发送消息")
					reject(false)
		    	}
		    })
		})
	},
	// 启动心跳 start
	start() {
		this.timeoutObj = setInterval(() => {
			const message = {
				cmd: 0,
				user_id: this.userId,
				content: "ping"
			}
			uni.sendSocketMessage({
				data: JSON.stringify(message),
				success: (res) => {
					console.log('心跳连接成功....')
				},
				fail: (err) => {
					console.log('心跳连接失败重新连接....')
					this.openConnection()
				}
			});
		}, this.timeout);
	},
	// 处理当前页的消息
	currentPageMessage(reData, key) {
		var pages = getCurrentPages()
		var len = pages.length
		for (var i = 0; i < len; i++) {
			var page = pages[i]
			console.log(page.route)
			if (page.route == 'pages/message/chat/chat') {
				page.$vm.recvMsg(reData)
			} else if (page.route == 'pages/message/groupChat/groupChat') {
				page.$vm.recvMsg(reData)
			} else if(page.route == 'pages/message/message') {
				let data = JSON.parse(reData)
				data.count = 1
				page.$vm.recvMsg(data)
			} else {
				let data = JSON.parse(reData)
				data.count = 1
				store.dispatch('addNewMessage', JSON.stringify(data))
			}
		}
	}
}